package com.example.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * ClassName: zkClient
 * Package: com.example.zk
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-29
 * Time: 22:02
 */

public class zkClient {

    //前后左右都没有空格
    private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    //超时时间 2000毫秒
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;

    //创建执行环境
    @Before
    public void init() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                List<String> children = null;
                try {
                    //初始化这个监听 用一次就失效了 在用的时候就在 ture 就是再用一次 反复
                    children = zooKeeper.getChildren("/", true);
                    for (String child : children) {
                        System.out.println(child);
                    }
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //创建子节点
    @Test
    public void create() throws InterruptedException, KeeperException {
        String nodeCreate =
                zooKeeper.create("/atguigu", "ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    //获取节点并监听节点变化
    @Test
    public void getChildren() throws InterruptedException, KeeperException {
        //第二个参数 Watcher 就是初始化的Watcher
        List<String> children = zooKeeper.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }

        //监听的前提程序不结束
        //怎么不结束 延迟一会
        Thread.sleep(Long.MAX_VALUE);
    }


    //判断节点是否存在
    @Test
    public void exist() throws InterruptedException, KeeperException {
        Stat exists = zooKeeper.exists("/sanguo", false);

        System.out.println(exists == null ? "not exist" : "exist");
    }

}
